/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Alert;
import com.riq.entity.Department;
import com.riq.entity.Location;
import com.riq.entity.Member;
import com.riq.entity.Status;
import com.riq.entity.Tracking;

//@SuppressWarnings("serial")
public class KeyMetricsServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;
  private static final Logger log = Logger.getLogger(Tracking.class.getName());
  private Long alertCount = Long.valueOf("0");
  private Long alertTotalTracks = Long.valueOf("0");
  private Long alertMembers = Long.valueOf("0");
  private Long alertRespOneNo = Long.valueOf("0");
  private Long alertRespOneYes = Long.valueOf("0");
  private Long alertRespVoiceMissed = Long.valueOf("0");
  private Long alertRespVoiceComplete = Long.valueOf("0");
  private Long alertRespWeb = Long.valueOf("0");
  private Long alertRespAdHoc = Long.valueOf("0");
  private Long alertRespNull = Long.valueOf("0");  
  private Long nonMemberTracks = Long.valueOf("0");
  private String flagMutualAid = "";

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
   
    PersistenceManager pm = PMF.get().getPersistenceManager();
        
    // format elapsed time
    SimpleDateFormat dateFormat = new SimpleDateFormat("w");
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM");
    Long id = Long.valueOf("101524");
    
    // ALL DEPTS    
    Query queryD = pm.newQuery(Department.class);
    queryD.setOrdering("id asc");
    List<Department> departments = (List<Department>)queryD.execute();
    
    // ALL MEMBERS    
    Query queryA = pm.newQuery(Alert.class);
    queryA.setOrdering("deptId asc");
    List<Alert> alerts = (List<Alert>)queryA.execute();
    
    // ALL MEMBERS    
    Query queryM = pm.newQuery(Member.class);
    queryM.setOrdering("deptId asc");
    List<Member> members = (List<Member>)queryM.execute();
    log.info("Members: " + members.size());
    
    // ALL STATUSES
    Query queryS = pm.newQuery(Status.class);
    queryS.setOrdering("deptId asc");
    List<Status> statuses = (List<Status>)queryS.execute();

    // ALL LOCATIONS
    Query queryL = pm.newQuery(Location.class);
    queryL.setOrdering("deptId asc");
    List<Location> locations = (List<Location>)queryL.execute();

    // ALL TRACKS
    // gather all the tracks for this one alert, order by member asc, time desc
    String qTracks =  " select from " + Tracking.class.getName() + 
    " order by deptId asc, timeStamp asc";
    List<Tracking> tracks = (List<Tracking>) pm.newQuery(qTracks).execute(); 

    PrintStream out;
    
    response.setContentType("text/html");
    out = new PrintStream(response.getOutputStream());

    for (Department d : departments) {
        alertCount = Long.valueOf("0");

    	out.println("DEPT: " + d.getshortName() + "<br>");
        out.println("---------------------------------------<br>");
    	
    	// alertCount
        for (Alert a : alerts) {
    	    if (a.getdeptId().equals(d.getid())) {
    	    	alertCount++;
    	    }
        }
        out.println("Alerts: " + alertCount + "<br>");
        out.println("<br>");
    	alertTotalTracks = Long.valueOf("0");
    	alertMembers = Long.valueOf("0");
        for (Alert a : alerts) {
        	
//          int addrEnd = 0;
//          addrEnd = a.getalertMsgString().indexOf("[") - 1;
          if (a.getdeptId().equals(d.getid())) {
              out.println("ALERT: " + a.getalertMsgString().substring(0, 15));        	

            String tempDeptId = "";
            // tracks per alert (more tracks, more utilization)        
            for (Tracking t1 : tracks) {
              // used for mutual aid calc later in code	
	    	  tempDeptId = t1.getdeptId().toString();
      	      if (t1.getalertId().equals(a.getid())) {
    	     	  alertTotalTracks++;
    	      }
            }
    	    
            
            
	        for (Tracking t2 : tracks) {
	          if (a.getdeptId().equals(d.getid())) {

		        // members added by themselves over web per alert
	    	    if (t2.gettype().equalsIgnoreCase("member")) {
	    	   	  alertMembers++;
	        	  break;
	    	    }
	    	    
	            // members added by themselves over voice, sms or Android per alert 
	    	    else if (t2.gettype().equalsIgnoreCase("memberVoiceMissed")) {
	    	      alertRespVoiceMissed++;
	    	      break;
	    	    }
	    	    
	            // members added by themselves over voice, sms or Android per alert 
	    	    else if (t2.gettype().equalsIgnoreCase("memberVoiceComplete")) {
	    	      alertRespVoiceComplete++;
	    	      break;
	    	    }
	    	    
	            // members added by themselves over voice, sms or Android per alert 
	    	    else if (t2.gettype().equalsIgnoreCase("memberOneClickYes")) {
	    	      alertRespOneYes++;
	    	      break;
	    	    }
	    	    
	            // members added by themselves over voice, sms or Android per alert 
	    	    else if (t2.gettype().equalsIgnoreCase("memberOneClickNo")) {
	    	      alertRespOneNo++;
	    	      break;
	    	    }
	    	    
	            // members added by Command per alert 
	    	    else if (t2.getresponseType().equalsIgnoreCase("resourceAddMember")) {
	    	      alertRespAdHoc++;
	    	      break;
	    	    }
	    	    
	    	    else { nonMemberTracks++; }
	    	    
	    	    // check for mutual aid (more than one deptId in alert tracks)
	    	    if (t2.getdeptId().equals(tempDeptId)) {
	    	    	flagMutualAid = "yes";
	    	    }
	    	      
	          } // if
	        } // for tracks t1 

          out.println("<br>");
          out.println(alertTotalTracks + "|" + 
        		  	  alertMembers + "|" + 
        		      alertRespVoiceMissed + "|" + 
        		      alertRespVoiceComplete + "|" + 
        		      alertRespOneYes + "|" + 
        		      alertRespOneNo + "|" + 
        		      alertRespAdHoc + "|" + 
        		      nonMemberTracks + "<br><br>");
  	      out.flush();
          
          alertRespVoiceMissed = Long.valueOf("0");
	      alertRespOneYes = Long.valueOf("0");
	      alertRespOneNo = Long.valueOf("0");
	      alertRespAdHoc = Long.valueOf("0");
	      nonMemberTracks = Long.valueOf("0");
          } // if
          
        alertMembers = Long.valueOf("0");
        alertTotalTracks = Long.valueOf("0");
        } // for alerts
          
    }
    	            	
    	            	
    	            	
	out.println("DeptId|DeptName|DeptLat|DeptLng|AlertId|AlertLat|AlertLng|" + 
	"TrackLocation|LocationType|LocationName|TrackTimestamp|TrackId|StatusId|TrackType|TrackId");
    	          
    for (Department d1 : departments) {
        out.println(d1.getshortName());

      for (Alert a1 : alerts) {
	    if (a1.getdeptId().equals(d1.getid())) {
	    	alertCount = alertCount + 1;
	      for (Tracking t1 : tracks) {
	        if (t1.getalertId().equals(a1.getid())) {		
	          for (Location l1 : locations) {
	            if (l1.getid().equals(t1.getlocationId())) {
	          
	              out.println(d1.getid().toString() + "|" +
	    			      d1.getshortName().toString() + "|" +
	    				  d1.getcoordinatesLatitude() + "|" +
	    				  d1.getcoordinatesLongitude() + "|" +
	    				  a1.getid().toString() + "|" +
	    				  a1.getlat() + "|" +
	    				  a1.getlng() + "|" +
	    				  t1.getlocationId().toString() + "|" +
	    				  l1.gettype() + "|" + 
	    				  l1.getshortName() + "|" +
	    				  t1.gettimeStamp().toString() + "|" +
	    				  t1.getid().toString() + "|" +
//	    				  t1.getstatusKey() + "|" +
	    				  t1.gettype().toString() + "|" +
	    				  t1.gettypeId().toString() + "<br>");
	              
		            }
		          }
	    		}
	    	  }
	    	}
	      }
	    }
	    out.flush();
	    out.close();
	  }
  
}

